import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import { API_BASE_URL, REQUEST_TIMEOUT } from './config'
import { apiMonitor } from '@/utils/apiMonitor'

// 创建读操作API实例
const readApi: AxiosInstance = axios.create({
    baseURL: API_BASE_URL.READ,
    timeout: REQUEST_TIMEOUT,
    headers: {
        'Content-Type': 'application/json'
    }
})

// 创建写操作API实例
const writeApi: AxiosInstance = axios.create({
    baseURL: API_BASE_URL.WRITE,
    timeout: REQUEST_TIMEOUT,
    headers: {
        'Content-Type': 'application/json'
    }
})

// 请求拦截器
const requestInterceptor = (config: any) => {
    // 添加认证token
    const token = localStorage.getItem('token')
    if (token) {
        config.headers = {
            ...config.headers,
            'Authorization': `Bearer ${token}`
        }
    }

    // 记录请求开始时间
    config.startTime = Date.now()

    // 调试信息：打印完整的请求URL
    const fullUrl = `${config.baseURL}${config.url}`
    console.log('API请求URL:', fullUrl)
    console.log('请求参数:', config.params)

    return config
}

// 响应拦截器
const responseInterceptor = (response: AxiosResponse) => {
    const startTime = (response.config as any).startTime
    const duration = Date.now() - startTime

    // 记录成功的请求
    const isRead = response.config.baseURL === API_BASE_URL.READ
    apiMonitor.logRequest(
        response.config.method?.toUpperCase() || 'GET',
        response.config.url || '',
        isRead ? 'READ' : 'WRITE',
        duration,
        response.status,
        true
    )

    return response.data
}

const errorInterceptor = (error: any) => {
    const startTime = (error.config as any)?.startTime
    const duration = startTime ? Date.now() - startTime : 0

    // 记录失败的请求
    const isRead = error.config?.baseURL === API_BASE_URL.READ
    apiMonitor.logRequest(
        error.config?.method?.toUpperCase() || 'GET',
        error.config?.url || '',
        isRead ? 'READ' : 'WRITE',
        duration,
        error.response?.status || 0,
        false
    )

    console.error('API请求错误:', error)
    return Promise.reject(error)
}

// 添加拦截器
readApi.interceptors.request.use(requestInterceptor)
readApi.interceptors.response.use(responseInterceptor, errorInterceptor)

writeApi.interceptors.request.use(requestInterceptor)
writeApi.interceptors.response.use(responseInterceptor, errorInterceptor)

// 导出API实例
export { readApi, writeApi }

// 通用请求方法
export const apiRequest = {
    // 读操作
    get: (url: string, params?: any) => readApi.get(url, { params }),
    // 写操作
    post: (url: string, data?: any) => writeApi.post(url, data),
    put: (url: string, data?: any) => writeApi.put(url, data),
    delete: (url: string) => writeApi.delete(url),
    patch: (url: string, data?: any) => writeApi.patch(url, data)
} 